package com.mywebsite.Service.Impl;

import com.mywebsite.Domain.EmailCode;
import com.mywebsite.Service.EmailService;
import com.mywebsite.Utils.CheckEmailCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Random;

@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    JavaMailSenderImpl mailSender;
    @Autowired
    CheckEmailCode checkEmailCode;


    @CachePut(value = "EmailVfCode",key = "#useremail")
    public String sendEmail(String useremail)  {
        try {
            //授权码：ahmwjqcttixdecaa

            int count = 1;//默认发送一次
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            while (count-- != 0) {
                String codeNum = "";
                int[] code = new int[3];
                Random random = new Random();
                //自动生成验证码
                for (int i = 0; i < 6; i++) {
                    int num = random.nextInt(10) + 48;
                    int uppercase = random.nextInt(26) + 65;
                    int lowercase = random.nextInt(26) + 97;
                    code[0] = num;
                    code[1] = uppercase;
                    code[2] = lowercase;
                    codeNum += (char) code[random.nextInt(3)];
                }
                //标题
                helper.setSubject("您的验证码为：" + codeNum);
                //内容
                helper.setText("注册成功!,您的验证码为：" + "<h2>" + codeNum + "</h2>" + "验证码在5分钟之内有效！", true);
                //邮件接收者
                helper.setTo(useremail);
                //邮件发送者，必须和配置文件里的一样，不然授权码匹配不上
                helper.setFrom("emailsender.real@qq.com");
                mailSender.send(mimeMessage);
                System.out.println("邮件发送成功！请求邮箱:"+useremail + (count + 1));

                return codeNum;
            }
        }catch (Exception e){
            System.out.println("邮件发送失败，请求邮箱:"+useremail);
            return "Error";
        }
            return "Error.Send_Failed";
    }


    public Boolean checkEmail(EmailCode emailCode) {
        String checkcode = emailCode.getVfCode();
        String cacheCode = checkEmailCode.get(emailCode.getUserEamil());
        return checkcode.equals(cacheCode);

    }

}
